﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Hotnet.Dal.BaseRepository;
using Hotnet.Entity;
using Hotnet.Entity.Search;
using Hotnet.Entity.Enum;
using Hotnet.Entity.View;
using Hotnet.Dal.Utility;

namespace Hotnet.Dal.NSDalVideo
{
	public class DalVideoList : Repository<VideoList>
	{
		public ViewVideoList[] List(SearchVideoList condition, int pageNo, int pageSize, out int totalCount)
		{
			int from = pageNo * pageSize + 1;
			int to = (pageNo + 1) * pageSize;
			totalCount = 0;

			string listTypeCondition = "";
			string orderByCondition = "";
			string groupNameCondition = "";
			string isPublishedCondition = "";
			string videoCategoryCondition = "";

			if (condition.ListType != null)
				listTypeCondition = string.Format(" and ListType={0} ", (int)condition.ListType);
			if (condition.OrderType == Hotnet.Entity.Enum.EnumOrder.添加时间 || condition.OrderType == null)
				orderByCondition = " VideoList.IsPublished,VideoList.AddTime ";
			else
				orderByCondition = " VideoList.IsPublished,ClickCount ";
			if (!string.IsNullOrEmpty(condition.VideoName))
				groupNameCondition = string.Format(" and Name like '%{0}%'", condition.VideoName);
			if (condition.VideoCategroyId != null)
				videoCategoryCondition = string.Format(" and CategoryID={0}", condition.VideoCategroyId);
			if (condition.IsPublished != null)
				isPublishedCondition = string.Format(" and VideoList.IsPublished={0} ", (int)condition.IsPublished);

			string strSql = string.Format(@"select * from (SELECT ROW_NUMBER() OVER (ORDER BY {5} desc)AS Row,
										Video.VideoID, 
										Video.Name,
										Video.Description,
										Video.VideoSrc,
										Video.DownLoadUrl,
										Video.IsDVD,
										Video.IsCanPlayInner, 
										Video.CategoryID,
										Video.CoverImagePath,
										Video.Director,
										Video.Zone,
										Video.PreviewTime,
										Video.SourceFromID, 
										VideoList.AddTime,
										Video.DefineType,
										Video.ClickCount,
										Video.IsGroup,
										Video.IsPublished,
										VideoList.ListType, 
										VideoList.CoverImageSrc,
										VideoList.IsPublished AS VideoListIsPublished
										FROM [VideoList] join Video on Video.VideoID=VideoList.VideoID where 1=1 {0} {1} {2} {6} {7}) t1 WHERE Row between {3} and {4}", listTypeCondition, groupNameCondition, isPublishedCondition, from, to, orderByCondition, videoCategoryCondition, isPublishedCondition);
			string strCount = string.Format(@"SELECT count(*) 
										FROM [VideoList] join Video on Video.VideoID=VideoList.VideoID where 1=1 {0} {1} {2} {3} {4}", listTypeCondition, groupNameCondition, isPublishedCondition, videoCategoryCondition, isPublishedCondition);
			totalCount = disableCacheDataContext.ExecuteQuery<int>(strCount).FirstOrDefault();
			return disableCacheDataContext.ExecuteQuery<ViewVideoList>(strSql).ToArray();
		}
	}
}
